﻿#include "stdafx.h"
#include "ClassInstanceType.h"
#include "AstClass.h"
#include "AstFunction.h"
#include "FunctionInstance.h"
#include "SiContext.h"
#include "utility.h"
#include "ClassContext.h"
#include "CodeGenerate/CodeGen.h"
#include "utility.h"

int ClassInstanceType::serial = 0;

ClassInstanceType::ClassInstanceType(const std::string& n) 
	: AstType( StructTyID )
{
	this->name = n;
	_uname = "C" + (n.size() < 10 ? n : n.substr(0, 10)) + i2hexString(serial++);
}

std::string ClassInstanceType::uniqueName()
{
	return _uname;
}

using namespace llvm;
Type * ClassInstanceType::llvmType(LLVMContext & context)
{
	if (_type) return _type;
	std::vector< Type* > types;

	std::string n;
	int index = 0;
	for (auto &i : members) {
		AstType* a = i.second.type;
		i.second.index = index++;
		auto *p = a->llvmType(context);
		assert(p);
		types.push_back(p);

		n.push_back('.');
		n += a->uniqueName();
	}

	// 按类型创建独一无二的名称
	n = n.empty() ? name : name + "_" + encodeByHash(n);
	if( types.empty())
		_type= StructType::create(context,  n);
	else
	_type = StructType::create(context, types, n);
	return _type;
}

SiContext * ClassInstanceType::makeContext(SiContext * context, CodeGen * codeGen)
{
	return new ClassContext(context, codeGen);
}

